<?php

namespace App\Http\Controllers\Wx;

use App\Http\Controllers\Controller;
use App\Model\Student;
use App\Model\StudentClass;
use Illuminate\Http\Request;
use Illuminate\Support\Str;

/**
 * wx小程序学生报名
 */
class StudentController extends Controller
{

    public function getClassList(Request $request)
    {

        $class_type = $request->class_type;

        // 只显示在报名时间之内的班级
        $query = StudentClass::select('*')
            ->where([
                ['sign_start_time', '<=', millisecond()],
                ['sign_end_time', '>=', millisecond() - 86400 * 1000],
            ])
            ->orderBy('class_start_time', 'ASC');

        if ($class_type) {
            $query->where('class_type', $class_type);
        }
        $result = $query->get();
        // $result = $result->groupBy('class_type');
        return resJson(self::HTTP_0_SUCCESS, $result);
    }

    /**
     * 报名
     *
     * @return void
     */
    public function enter(Request $request)
    {
        $inputs = $request->all();
        $find = Student::where('wx_openid', $inputs['wx_openid'])->first();
        if ($find && $find->status == 1) {
            // 已经审核通过
            return resJson(self::CUSTOM_10005_NOEDIT_ERROR);
        }
        $inputs['status'] = 0; // 审核中

        // 生成一个123456的默认密码
        $salt = Str::random(10);
        $password = 123456;
        $inputs['password'] = encrypt_password($password, $salt);
        $inputs['salt'] = $salt;
        // 生成应收费用
        $inputs['receivable_fee'] = StudentClass::where('id', $inputs['class_id'])->value('class_fee') ?: 0;

        $inputs['created_time'] = millisecond();
        if ($find) {
            $student = Student::find($find->id);
            $student->fill($inputs);
            $student->save();
        } else {
            $student = Student::Create($inputs);
        }

        return resJson(self::HTTP_0_SUCCESS, $student);
    }

    /**
     * 报名状态
     */
    public function status(Request $request)
    {
        $open_id = $request->open_id;
        $status = Student::where('open_id', $open_id)->value('status');
        if ($status === null) {
            return resJson(self::HTTP_0_SUCCESS, ['status' => -1]);
        } else {
            return resJson(self::HTTP_0_SUCCESS, ['status' => $status]);
        }
    }

    /**
     * 学生信息
     */
    public function info(Request $request)
    {
        $openid = $request->header('openid');
        $student = Student::where('wx_openid', $openid)->first();
        if ($student) {
            $classInfo = StudentClass::select('class_type', 'class_name', 'class_start_time', 'class_fee')->find($student->class_id);
            $student->class = $classInfo;
        }
        return resJson(self::HTTP_0_SUCCESS, $student);
    }
}
